package com.acmedcare.framework.exchange.center.core.handler;

import com.acmedcare.framework.exchange.center.core.Const;
import com.acmedcare.framework.exchange.center.core.PluginContainerMBean;
import com.acmedcare.framework.exchange.center.core.storage.StageRepository;
import com.acmedcare.framework.exchange.center.entity.bean.StageConfig;
import com.acmedcare.framework.exchange.center.entity.dto.StageDetailDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StageCommandHandler {

  final ObjectMapper objectMapper;

  final PluginContainerMBean pluginContainer;

  final StageRepository stageRepository;

  public StageCommandHandler(ObjectMapper objectMapper,
      PluginContainerMBean pluginContainer, StageRepository stageRepository) {
    this.objectMapper = objectMapper;
    this.pluginContainer = pluginContainer;
    this.stageRepository = stageRepository;
  }

  @SuppressWarnings("unused")
  public void receive(String message) {

    log.info("接受到了环境变量指令:"+message);
    try {
      StageDetailDto stageDetailDto = objectMapper.readValue(message, StageDetailDto.class);
      String currentEnv = System.getenv(Const.GroupName);
      if (!stageDetailDto.getStage().getStageName().equals(currentEnv)) {
        log.info(String
            .format("当前环境:%s与发布环境:%s不匹配,不加载", currentEnv,
                stageDetailDto.getStage().getStageName()));
        return;
      }

      if (!stageDetailDto.getStageConfig().isEmpty()) {
        stageDetailDto.getStageConfig().stream().forEach(c -> {

          String currentValue = System.getProperty(c.getConfigName());
          if (currentValue == null || !currentEnv.equals(c.getConfigValue())) {

            log.info(String.format("当前环境:%s,正在写入环境变量,变量名称:%s,变量值:%s", currentEnv, c.getConfigName(),
                c.getConfigValue()));
            System.setProperty(c.getConfigName(), c.getConfigValue());
            //通知插件环境变量值发生了变化
            pluginContainer.setEnv(c.getConfigName(),c.getConfigValue());

            try {
              stageRepository.delete(c.getConfigId());
              stageRepository.insert(c);
            } catch (Exception e) {
              log.warn("环境配置写入数据库发生错误,错误信息:" + e.getMessage());
            }
          }
        });
      }
    } catch (IOException e) {
      log.error("获取环境变量信息错误,请确认信息是否正确!" + e.getMessage());
      return;
    }
  }

  public void loadConfig() {

    List<StageConfig> stageConfigs = stageRepository.getConfigs();
    if (stageConfigs != null && !stageConfigs.isEmpty()) {
      stageConfigs.forEach(c ->
          pluginContainer.setEnv(c.getConfigName(),c.getConfigValue()));
    }
  }
}